package mk.com.ldm.corepoint.implementation.client.lib.custom.listview;

import java.util.HashMap;
import java.util.LinkedList;

import mk.com.ldm.corepoint.implementation.client.CoreService;
import mk.com.ldm.corepoint.implementation.client.CoreServiceAsync;
import mk.com.ldm.corepoint.implementation.client.lib.custom.cpstable.ActionEvent;
import mk.com.ldm.corepoint.implementation.client.lib.custom.cpstable.ActionEventHandler;
import mk.com.ldm.corepoint.implementation.client.lib.custom.cpstable.CustomPagingScrollTable;
import mk.com.ldm.corepoint.implementation.client.lib.generators.AddEvent;
import mk.com.ldm.corepoint.implementation.client.lib.generators.AddEventHandler;
import mk.com.ldm.corepoint.implementation.client.lib.generators.BaseWidget;
import mk.com.ldm.corepoint.implementation.client.lib.validation.Validator;
import mk.com.ldm.corepoint.implementation.client.presenter.EditPresenter;
import mk.com.ldm.corepoint.implementation.client.view.EditView;
import mk.com.ldm.corepoint.implementation.client.view.ModalOverlay;
import mk.com.ldm.corepoint.implementation.shared.Filter;
import mk.com.ldm.corepoint.implementation.shared.FormRow;
import mk.com.ldm.corepoint.implementation.shared.TemporaryStorage;

import org.gwt.mosaic.ui.client.InfoPanel;
import org.gwt.mosaic.ui.client.LayoutPopupPanel;
import org.gwt.mosaic.ui.client.MessageBox;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;

public class ListView extends BaseWidget {

	private Label label = new Label();
	private TextBox textbox = new TextBox();
	private Button searchButton = new Button(this.SEARCH_IMAGE);
	private Button editButton = new Button(this.EDIT_IMAGE);
	private CustomPagingScrollTable pTable;
	CoreServiceAsync rpcService = GWT.create(CoreService.class);
	FormRow config;
	
	public ListView(FormRow config, HandlerManager eventBus) {
		super(config);
		
		this.config = config;
		
		this.setType(11);
		label.setText(config.getNam());
		label.setWidth(this.LABEL_WIDTH);
		textbox.setName(config.getDbn());
		textbox.setTabIndex(config.getTab());
		textbox.setWidth(this.TEXTBOX_WIDTH);
		
		if(!config.getVal().isEmpty()){
			if(config.getVal().split(":/#").length>1){
				textbox.setValue(config.getVal().split(":/#")[0]);
				textbox.setTitle(config.getVal().split(":/#")[1]);
			}
			else
				textbox.setValue(config.getVal());
		}
		
		if(config.getEna() == 0){
			textbox.setEnabled(false);
			searchButton.setEnabled(false);
			editButton.setEnabled(false);
		}
		if(config.getVis() == 0){
			textbox.setVisible(false);
			label.setVisible(false);
			searchButton.setVisible(false);
			editButton.setVisible(false);
		}
		
		
		searchButton.setTabIndex(999999);
		editButton.setTabIndex(999999);
		
		HorizontalPanel hp = new HorizontalPanel();
		hp.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		hp.add(label);
		hp.add(textbox);
		hp.add(searchButton);
		hp.add(editButton);
		
		setEvents(config.getTag(), eventBus);
				
		initWidget(hp);
		
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void setEvents(final String tags, final HandlerManager eventBus){
		
		final LayoutPopupPanel winModal = new LayoutPopupPanel();
		winModal.setModal(false);
		winModal.setGlassEnabled(false);
		winModal.setStyleName("ui-Suggest");
		winModal.setHeight("220px");
		
		
		winModal.setAutoHideEnabled(true);

		
		final String name = tags.split(",")[1].split("/")[0];
		final String[] filters = tags.split(",")[1].split("/");
		
		pTable = new CustomPagingScrollTable();
		pTable.setInitialUse(true);
		pTable.setRpcService(rpcService);
		pTable.setUsername("");
		pTable.setObjectName(tags.split(",")[0]);
		pTable.setObjectType("List");
		pTable.setType(CustomPagingScrollTable.SELECT);
		pTable.getTable().setWidth("500px");
		pTable.getTable().setHeight("200px");
		pTable.setStyleName("ui-Suggest-table");
		
		pTable.addActionEventHandler(new ActionEventHandler(){

			@Override
			public void onEdit(ActionEvent event) {
				textbox.setText(event.getRow().get(name));
				setGroupValues(tags, event.getRow().getMap());
				textbox.setTitle(event.getRow().get(tags.split(",")[2]));
				textbox.removeStyleName("ui-Invalid");
				textbox.setFocus(true);
				textbox.setFocus(false);
				textbox.setFocus(true);
				winModal.hide();
			}
			
		});
		
		winModal.addCloseHandler(new CloseHandler<PopupPanel>() {
			
			@Override
			public void onClose(CloseEvent<PopupPanel> event) {
				searchButton.setEnabled(true);
				searchButton.setHTML(ListView.this.SEARCH_IMAGE);
				ModalOverlay.hide();
			}
		});
				
		searchButton.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
				searchButton.setEnabled(false);
				searchButton.setHTML(ListView.this.LOADING_IMAGE);
				textbox.setFocus(true);
				

				if(!textbox.getText().isEmpty()){
					for(String fil:filters){
						HashMap<String,String> value = new HashMap<String,String>();
						value.put(fil, textbox.getValue());
						Filter filter  = new Filter(fil, value, "LIKE" );
						pTable.addFilter(filter,fil);
					}
				}
				else{
					for(String fil:filters){
						pTable.removeFilter(fil);
					}
				}

			
				winModal.setWidget(pTable);
				
				pTable.fillTable();
				winModal.setWidget(pTable);
				winModal.pack();
				DOM.setStyleAttribute(winModal.getElement(), "top", textbox.getAbsoluteTop()+20+"px");
				DOM.setStyleAttribute(winModal.getElement(), "left", textbox.getAbsoluteLeft()+"px");
				winModal.show();
				
			}
			
		});
		
		textbox.addKeyDownHandler(new KeyDownHandler() {
			
			@Override
			public void onKeyDown(KeyDownEvent event) {
				if(event.getNativeKeyCode()==13){
					searchButton.click();
				} else if(event.getNativeKeyCode() == 27){
					winModal.hide();
				}
			}
			
			
		});
		
		textbox.addKeyUpHandler(new KeyUpHandler() {
			
			@Override
			public void onKeyUp(KeyUpEvent event) {
//				InfoPanel.show("", event.getNativeKeyCode()+"");
				if(!textbox.getValue().equals("")&&textbox.getValue().length()>2&&event.getNativeKeyCode()!=27&&event.getNativeKeyCode()!=9
						&&event.getNativeKeyCode()!=16&&event.getNativeKeyCode()!=17)
					searchButton.click();
				if(textbox.getValue().equals("")&&event.getNativeKeyCode()!=13)
					winModal.hide();
			}
		});
		
		textbox.addBlurHandler(new BlurHandler(){

			@Override
			public void onBlur(BlurEvent event) {
				if(!textbox.getValue().isEmpty() && textbox.getTitle().isEmpty()){
					Validator.getInstance().validateListView(config, textbox, ListView.this);	
				}
			}
			
		});
		
		textbox.addFocusHandler(new FocusHandler(){

			@Override
			public void onFocus(FocusEvent event) {
				String styles = textbox.getStyleName();
				int indexOfInvalid = styles.indexOf("ui-Invalid");
				if(indexOfInvalid != -1){
					textbox.setValue("");
					textbox.removeStyleName("ui-Invalid");
				}
				textbox.setTitle("");
			}
			
		});
				
		editButton.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
				EditPresenter editPresenter = new EditPresenter(rpcService, eventBus, new EditView("Edit", tags.split(",")[0]), "Edit", 
						tags.split(",")[0], null, "");
				editPresenter.setListViewTextBox(textbox);
				editPresenter.setListViewReturn(tags.split(",")[1].split("/")[0]);
				editPresenter.go(editPresenter.getDisplay().getWindow());
				editPresenter.getFormGenerator().addAddEvent(new AddEventHandler() {
					@Override
					public void onAdd(AddEvent event) {
						textbox.setTitle(event.getId());
						textbox.setValue(event.getName());
					}
				});
//				eventBus.fireEvent(new NavigationEvent(" ",tags.split(",")[0], ""));
			}

		
			
		});
		
	}
	
	public void setGroupValues(String tag, HashMap<String, String> values){
		
		String groupName = tag.split(",")[0];
		
		HashMap<String, BaseWidget> groupList = TemporaryStorage.getInstance().getGroups().get(groupName);
		
		LinkedList<FormRow> widgetList = TemporaryStorage.getInstance().getForm().getConfRows();
		
		for(FormRow row:widgetList){
			if(groupList.get(row.getTag().split(",")[0]) != null){
				BaseWidget member = groupList.get(row.getTag().split(",")[0]);
				member.setValue(values.get(row.getTag().split(",")[1]));
			}
		}
	}

	public Label getLabel() {
		return label;
	}

	public void setLabel(Label label) {
		this.label = label;
	}

	public TextBox getTextbox() {
		return textbox;
	}

	public void setTextbox(TextBox textbox) {
		this.textbox = textbox;
	}

	public Button getSearchButton() {
		return searchButton;
	}

	public void setSearchButton(Button searchButton) {
		this.searchButton = searchButton;
	}

	public Button getEditButton() {
		return editButton;
	}

	public void setEditButton(Button editButton) {
		this.editButton = editButton;
	}

	public CustomPagingScrollTable getTable() {
		return pTable;
	}

	public void setTable(CustomPagingScrollTable pTable) {
		this.pTable = pTable;
	}
	
	public void setEditButtonVisible(boolean visible){
		editButton.setVisible(visible);
	}

	@Override
	public void setValue(String value){ textbox.setValue(value);}
	@Override
	public String getValue(){ return textbox.getValue(); }
	@Override
	public void setEnabled(Boolean enabled) {textbox.setEnabled(enabled);}
	@Override
	public void setVisible(Boolean visible) {textbox.setVisible(visible); label.setVisible(visible);}
	@Override
	public void setTitle(String title) {textbox.setTitle(title);}
	@Override
	public String getTitle() {return textbox.getTitle();}
	@Override
	public String getText() {return label.getText();}
	@Override
	public void setText(String text) { label.setText(text); }
	@Override 
	public String getName(){ return textbox.getName(); }
	@Override
	public void setName(String name){ textbox.setName(name);}
	@Override
	public void setFocus(boolean focus){textbox.setFocus(focus);}
	
}
